define(['config', 'text!app/module/system/addLossRelation.html', 'laypage',
    'mydialog', 'autocomplete', 'jqGrid', 'common', 'laydate'
], function (config, viewHTML, laypage,
             mydialog, autocomplete, jqGrid, common, laydate) {

    var token = (cache.go("token") === 'undefined') ? 'none' : cache.go("token");

    var grid_arr = new Array();


    var model = avalon.define({
        $id: "addLossRelation",
        // 查询条件
        query: {},
        lossInfo: {
        	 id: "",
             name: "",
             status: "0",
             describes: "",
             remarks: "",
             businesslistId: "",
             createUser: "admin"
        },
        materialInfo: {
            id: "",
            sku: "",
            name: "",
            model: "",
            unit: "",
            remarks: "",
            decCm:"",
            decDm:"",
            goodsUuid:"",
            bomNo:""
        },


        statusArr: [],
        selected: [],
        roles: [],

        init: function () {
            model.initPage();
            model.addEvent();
        },
        initPage: function () {
            function t(val, opt, row) {
                var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="index.html#!/108"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';

                return html_con;
            }
//            var i = Public.setGrid();
//            var bomNo = Public.getQueryString("bomNo");
//            if (bomNo=="") {
//                $.ajax({
//                    type: "POST",
//                    url: "/api/loss/getBomNo",
//                    success: function (data) {
//                        model.lossInfo.bomNo = data;
//                        model.materialInfo.bomNo = data;
//                    },
//                    beforeSend: function (xhr) {
//                        xhr.setRequestHeader("X-AuthToken", token);
//                    },
//                    error: function (responseData, textStatus, errorThrown) {
//                        alert("Failed: " + responseData);
//                    }
//                });
//            }else {
//                model.lossInfo.bomNo = bomNo;
//                model.materialInfo.bomNo = bomNo;
//            }
            model.initloss();
            model.initmaterial();

               /* $.ajax({
                    type: "POST",
                    url: "/api/loss/findBomByBomNo",
                    data: {
                        "bomNo": bomNo
                    },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                    success: function (data) {
                        if(data.success){
                            if(data.data!=null){
                                model.lossInfo = data.data;
                                model.lossInfo.createDate = Public.custDatefmter(model.lossInfo.createDate);
                            }
                            $("#grid").jqGrid({
                                datatype: "json",
                                mtype: "POST",
                                url: 'api/loss/findByBomNo',
                                postData: {
                                    "bomNo": bomNo
                                },
                                loadComplete: function (data) {
                                },
                                colModel: [{
                                    name: "operating",
                                    label: "操作",
                                    width: '5%',
                                    formatter: t
                                },
                                    {
                                        name: "sku",
                                        label: "sku",
                                        width: '8%',
                                        hidden:true
                                    },
                                    {
                                        name: "bomNo",
                                        label: "bomNo",
                                        width: '8%',
                                        hidden:true
                                    },
                                    {
                                        name: "goodsUuid",
                                        label: "goodsUuid",
                                        width: '8%',
                                        hidden:true
                                    },
                                    {
                                        name: "name",
                                        label: "品名",
                                        width: '8%'
                                    },
                                    {
                                        name: "model",
                                        label: "规格",
                                        width: '10%'
                                    },
                                    {
                                        name: "unit",
                                        label: "计量单位",
                                        width: '10%',
                                    },{
                                        name: "decCm",
                                        label: "单耗/净耗",
                                        width: '10%',
                                    },
                                    {
                                        name: "decDm",
                                        label: "损耗率",
                                        width: '13%'
                                    },
                                    {
                                        name: "remarks",
                                        label: "备注",
                                        width: '13%'
                                    }
                                ],
                                page: 1,
                                rowNum: 10,
                                rowList: [10, 20, 30],
                                height: i.h,
                                autowidth: true,
                                pager: '#page',
                                sortname: 'id',
                                viewrecords: true,
                                forceFit: false,
                                rownumbers: true,
                                multiselect: true,
                                multiboxonly: true,
                                sortorder: "desc",
                                jsonReader: {
                                    root: "dataRows",
                                    records: "data.totalRow",
                                    total: "data.totalPage",
                                    repeatitems: false,
                                    id: "id"
                                }
                            });
                        }else{
                            parent.Public.tips({
                                type: 1,
                                content: "加载数据异常！"
                            })
                        }

                    },
                    error: function (responseData, textStatus, errorThrown) {
                        alert("Failed: " + responseData);
                    }
                });*/
        },

        //添加
        add: function () {
            model.initmaterial();
            dialog({
                title: '添加BOM信息',
                content: $('#editUser'),
                okValue: "确定",
                ok: function addRow() {
                    var selectedId = $("#grid").jqGrid("getGridParam", "selrow");
                    var rowData = model.materialInfo.$model;
                    rowData.bomNo = model.lossInfo.bomNo;
                    if(model.isEmpty(rowData.name.trim(),"品名不能为空!") &&  model.isEmpty(rowData.decCm.trim(),"单耗不能为空!") &&
                        model.isEmpty(rowData.decDm.trim(),"耗损率不能为空!")){
                        var rowid = new Date().getTime();
                        rowData.id = new Date().getTime();
                        if (selectedId) {
                            $("#grid").jqGrid("addRowData", rowid, rowData, "after", selectedId);
                        } else {
                            $("#grid").jqGrid("addRowData", rowid, rowData, "last");
                        }
                        grid_arr.push(rowData);
                    }else {
                        return false;
                    }

                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },


        /**删除商品*/
        del: function (id) {
            dialog({
                title: "确认操作",
                content: "确定删除？ 此操作不可恢复！",
                okValue: "确定",
                ok: function () {
                    for (var i = 0; i < grid_arr.length; i++) {
                        if (grid_arr[i].id == id) {
                            grid_arr.splice(i, 1);
                            $('#grid').jqGrid('delRowData', id);
//							var selectedId = $("#grid").jqGrid("getGridParam","selrow"); 
                            if (!id) {
                                alert("请选择要删除的行");
                                return;
                            } else {
                                $("#grid").jqGrid("delRowData", id);
                            }
                        }
                    }

                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },

        bindAutocomlete: function () {
            $("#sku").autocomplete({
                serviceUrl: "/api/goods/getGoodsBySku",
                paramName: "sku",
                minLength: 0,
                // 其他ajax配置
                ajaxSettings: {
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    }
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: '无匹配项',
                onSearchStart: function (query) {
                    // if (model.depart.parentID != "") {
                    //     model.depart.parentID = "";
                    // }
                },
                transformResult: function (response) {
                    var obj = $.parseJSON(response);
                    return {
                        suggestions: $.map(obj.data, function (data) {
                            return {
                                value: data.sku,
                                data: data
                            };
                        })
                    };
                },
                onSelect: function (suggestion) {
                    console.log('[suggestion.data]', suggestion.data);
                 //   model.lossInfo = suggestion.data;
                    model.lossInfo.goodsUuid = suggestion.data.uuid;
                    model.lossInfo.name = suggestion.data.name;
                    model.lossInfo.model = suggestion.data.model;
                    model.lossInfo.sku = suggestion.data.sku;
                },
                onSearchComplete: function (query, suggestions) {
                    $("div[data-index=0]").addClass("autocomplete-selected");
                }
            });
        },
        bindMaterialAutocomlete: function () {
            $("#goodsName").autocomplete({
                serviceUrl: "/api/goods/getMaterial",
                paramName: "name",
                minLength: 0,
                // 其他ajax配置
                ajaxSettings: {
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    }
                },
                showNoSuggestionNotice: true,
                noSuggestionNotice: '无匹配项',
                onSearchStart: function (query) {
                    // if (model.depart.parentID != "") {
                    //     model.depart.parentID = "";
                    // }
                },
                transformResult: function (response) {
                    var obj = $.parseJSON(response);
                    return {
                        suggestions: $.map(obj.data, function (data) {
                            return {
                                value: data.name,
                                data: data
                            };
                        })
                    };
                },
                onSelect: function (suggestion) {
                    console.log('[suggestion.data]', suggestion.data);
                    //   model.lossInfo = suggestion.data;
                    model.materialInfo.goodsUuid = suggestion.data.uuid;
                    model.materialInfo.model = suggestion.data.model;
                    model.materialInfo.unit = suggestion.data.unit;
                },
                onSearchComplete: function (query, suggestions) {
                    $("div[data-index=0]").addClass("autocomplete-selected");
                }
            });
        },
        edit: function (obj, t) {

            /**自动匹配商品*/

            model.materialInfo = $("#grid").jqGrid('getRowData', t);
            dialog({
                title: '编辑商品信息',
                content: $('#editUser'),
                okValue: "确定",
                ok: function addRow() {
                    var rowData = model.materialInfo.$model;
                    console.log('[rowData]', rowData);
                    var rowid = new Date().getTime();
                    rowData.id = new Date().getTime();
                    if(model.isEmpty(rowData.name.trim(),"品名不能为空!") &&  model.isEmpty(rowData.decCm.trim(),"单耗不能为空!") &&
                        model.isEmpty(rowData.decDm.trim(),"耗损率不能为空!")){
                    for (var i = 0; i < grid_arr.length; i++) {
                            $('#grid').jqGrid('delRowData', t);
                            $("#grid").jqGrid("addRowData", rowid, rowData);
                        }
                        grid_arr.splice(i, 1, rowData);
                    }
                    else {
                        return false;
                    }


                },
                cancelValue: "取消",
                cancel: function () {
                }
            }).showModal();
        },
        isEmpty: function (value, alerttxt) {
            if (value == null || value == "") {
                Public.tips({
                    type: 2,
                    content: alerttxt
                });
                return false;
            }
            else {
                return true;
            }
        },
        addEvent: function () {
            // //添加商品
            // $("#finishedPn").focus(function () {
            //     model.addGoods();
            // });
            $(".grid-wrap").on("click", ".fa-edit", function (e) {
                var t = $(this).parent().data("id");
                model.edit($("#grid").getRowData(t), t);
            });
            $(".fr").on("click", "#close", function (e) {
                top.topManager.closePage();
            });
            //提交表单
            $(".fr").on("click", "#save", function (e) {
                for (var i = 0; i < grid_arr.length; i++) {
                    grid_arr[i].id = "";
                }
                console.log(JSON.stringify(model.lossInfo));
                $.ajax({
                    contentType: "application/json",
                    type: "POST",
                    url: "/api/loss/save",
                    data: JSON.stringify(model.lossInfo),
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("X-AuthToken", token);
                    },
                    success: function () {
                    	dialog({
                            title: "提示",
                            content: "保存成功！",
                            okValue: "确定",
                            ok: function () {
                                location.replace('index.html#!/124');
                            }
                        }).showModal();
                       /* $.ajax({
                            contentType: "application/json",
                            type: "POST",
                            url: "/api/loss/saveMaterial",
                            data: JSON.stringify(grid_arr),
                            beforeSend: function (xhr) {
                                xhr.setRequestHeader("X-AuthToken", token);
                            },
                            success: function () {
                                dialog({
                                    title: "提示",
                                    content: "保存成功！",
                                    okValue: "确定",
                                    ok: function () {
                                        location.replace('index.html#!/124');
                                    }
                                }).showModal();
                            },
                            error: function (responseData, textStatus, errorThrown) {
                                alert("Failed: " +JSON.stringify(responseData) );
                            }
                        });*/
                    },
                    error: function (responseData, textStatus, errorThrown) {
                        alert("Failed: " + JSON.stringify(responseData));
                    }
                });
            });
            $(".grid-wrap").on("click", ".fa-trash-o", function (t) {
                var selectedId = $("#grid").jqGrid("getGridParam", "selrow");
                model.del(selectedId);

            });
        },
        initloss: function () {
            model.lossInfo = {
            		 id: "",
                     name: "",
                     status: "0",
                     describes: "",
                     remarks: "",
                     businesslistId: "",
                     createUser: "admin"
            }
        },
        initmaterial: function () {
            model.materialInfo = {
                id: "",
                sku: "",
                name: "",
                model: "",
                unit: "",
                remarks: "",
                decCm:"",
                decDm:"",
                goodsUuid:"",
                bomNo:model.initloss.bomNo
            }
        }

    });

    // 定义视图模块
    var viewmod = {
        viewtSrc: viewHTML,
        viewInit: function () {
            model.init();
        }, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
        viewDestroy: function () {
        } // 切换菜单时销毁原来的view
    };
    return viewmod;


});